package com.library.controller;

import com.library.entity.Book;
import com.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

//    @ModelAttribute
//    public void checkLogin(HttpSession session, HttpServletResponse response) throws IOException {
//        Boolean loggedIn = (Boolean) session.getAttribute("loggedIn");
//        if (loggedIn == null || !loggedIn) {
//            response.sendRedirect("/login.jsp");
//        }
//    }

    @GetMapping
    public String listBooks(Model model) {
        List<Book> books = bookService.getAllBooks();
        model.addAttribute("books", books);
        return "book/list";
    }

    @GetMapping("/list2")
    public String listBooks2(Model model) {
        List<Book> books = bookService.getAllBooks();
        model.addAttribute("books", books);
        return "book/list2";
    }

    @GetMapping("/add")
    public String showAddForm() {
        return "book/add";
    }

    @GetMapping("/edit")
    public String showEditForm(@RequestParam Integer id, Model model) {
        Book book = bookService.getBookById(id);
        model.addAttribute("book", book);
        return "book/edit";
    }

    @GetMapping("/search")
    public String searchBooks(@RequestParam String keyword, Model model) {
        List<Book> books = bookService.searchBooks(keyword);
        model.addAttribute("books", books);
        model.addAttribute("keyword", keyword);
        return "book/list2";
    }

    // RESTful API endpoints
    @ResponseBody
    @GetMapping("/api/books")
    public List<Book> getAllBooks() {
        return bookService.getAllBooks();
    }

    @ResponseBody
    @GetMapping("/api/books/{id}")
    public Book getBookById(@PathVariable Integer id) {
        return bookService.getBookById(id);
    }

    @ResponseBody
    @PostMapping("/api/books")
    public boolean addBook(@RequestBody Book book) {
        return bookService.addBook(book);
    }

    @ResponseBody
    @PutMapping("/api/books")
    public boolean updateBook(@RequestBody Book book) {
        return bookService.updateBook(book);
    }

    @ResponseBody
    @DeleteMapping("/api/books/{id}")
    public boolean deleteBook(@PathVariable Integer id) {
        return bookService.deleteBook(id);
    }
}